package com.bakar.dao;

import java.util.List;

import javax.jdo.annotations.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.bakar.util.DBUtil;
import com.bakar.valueobjects.MessageVO;
import com.bakar.valueobjects.UserVO;

public class MessageJPADAO implements MessageDAO {
	
	

	@SuppressWarnings("unchecked")
	@Override
	@Transactional 
	public List<MessageVO> getMessagesForUser(UserVO userVO) {
		EntityManager em = DBUtil.getInstanceEntityManagerFactory().createEntityManager();
		final  List<MessageVO> list = em.createQuery("select m from Messages m where toUser = ?1 order by id acs")
        .setParameter(1, userVO.getLoginId()).getResultList();
		for(MessageVO message : list){
			//System.out.println(message);
		}
		em.close();
		return list;

	}

	@SuppressWarnings("unchecked")
	@Override
	public void removeMessage(UserVO userVO) {
		EntityManager em = DBUtil.getInstanceEntityManagerFactory().createEntityManager();
		final  List<MessageVO> list = em.createQuery("select m from Messages m where toUser = ?1")
        .setParameter(1, userVO.getLoginId()).getResultList();
		for(MessageVO message : list){
			em.remove(message);
		}
		em.close();
	}

	@Override
	public void setMessage(MessageVO messageVO) {
		EntityManager em =  DBUtil.getInstanceEntityManagerFactory().createEntityManager();
		//EntityTransaction tx = em.getTransaction();
		//tx.begin();
		em.persist(messageVO);
		//tx.commit();
		em.close();

	}

/*	public static void main(String... args) {
		

		// First unit of work
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		UserVO user = new UserVO("Yogesh");
		user.setDisplayName("Yogi boy111");
		user.setImagePath("fff");
		user.setStatus("AVIALABLE");
		
		List<UserVO> friends  = new ArrayList<UserVO>();
		UserVO user11 = new UserVO("Yogesh");
		friends.add(user11);
		user.setMyFriends(friends);

		em.persist(user);
		em.merge(user);
		
		UserVO  myuser = em.find(UserVO.class, user.getLoginId());
		System.out.println(myuser.getAmFriends());
		tx.commit();
		em.close();
		
	}*/

}
